package com.base.server.file.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.base.server.file.dao.FileInfoDao;
import com.base.server.file.pojo.FileInfo;
import com.base.server.file.service.FileInfoService;
import com.ms.env.EnvUtil;
import com.system.comm.model.Page;
import com.system.comm.utils.FrameFileUtil;
import com.system.comm.utils.FrameJsonUtil;
import com.system.comm.utils.FrameNoUtil;
import com.system.comm.utils.FrameStringUtil;
import com.system.comm.utils.FrameTimeUtil;
import com.system.handle.model.ResponseCode;
import com.system.handle.model.ResponseFrame;

/**
 * file_info的Service
 * @author autoCode
 * @date 2019-07-13 16:27:06
 * @version V1.0.0
 */
@Component
public class FileInfoServiceImpl implements FileInfoService {

	private static final Logger LOGGER = LoggerFactory.getLogger(FileInfoServiceImpl.class);
	@Autowired
	private FileInfoDao fileInfoDao;
	private static final String[] UPLOAD_FILE_EXTS = new String[] {
			"doc", "docx",
			"txt", 
			"xls", "xlsx",
			"zip", "rar",
			"jpeg", "jpg", "png", "gif", "bmp",
			"mp4",
			"ppt", "pptx",
			"pdf" };

	private ResponseFrame saveFileInfo(FileInfo fileInfo) {
		ResponseFrame frame = new ResponseFrame();
		fileInfo.setFileId(FrameNoUtil.uuid());
		fileInfoDao.save(fileInfo);
		frame.setBody(fileInfo);
		frame.setCode(ResponseCode.SUCC.getCode());
		return frame;
	}

	@Override
	public FileInfo get(String fileId) {
		return fileInfoDao.get(fileId);
	}

	@Override
	public ResponseFrame pageQuery(FileInfo fileInfo) {
		fileInfo.setDefPageSize();
		ResponseFrame frame = new ResponseFrame();
		int total = fileInfoDao.findFileInfoCount(fileInfo);
		List<FileInfo> data = null;
		if(total > 0) {
			data = fileInfoDao.findFileInfo(fileInfo);
		}
		Page<FileInfo> page = new Page<FileInfo>(fileInfo.getPage(), fileInfo.getSize(), total, data);
		frame.setBody(page);
		frame.setCode(ResponseCode.SUCC.getCode());
		return frame;
	}

	@Override
	public ResponseFrame delete(String fileId) {
		ResponseFrame frame = new ResponseFrame();
		fileInfoDao.delete(fileId);
		frame.setCode(ResponseCode.SUCC.getCode());
		return frame;
	}

	@Override
	public FileInfo getByBrowseUrl(String browseUrl) {
		return fileInfoDao.getByBrowseUrl(browseUrl);
	}

	@Override
	public ResponseFrame save(MultipartFile multipartFile, FileInfo fileInfo) {
		ResponseFrame frame = new ResponseFrame();
		//获得原始文件名
		String orgName = multipartFile.getOriginalFilename();
		//String fileId = null;
		String fileExt = orgName.substring(orgName.lastIndexOf(".") + 1, orgName.length());
		String sysName = null;
		//为jpg||png||gif||bmp
		if(FrameStringUtil.isEqualsIcArrSin(fileExt, UPLOAD_FILE_EXTS)) {
			InputStream inputStream = null;
			try {
				inputStream = multipartFile.getInputStream();

				String savePath = EnvUtil.projectFilePath();
				//Long dateStr = System.currentTimeMillis();
				String browseDateDir = FrameTimeUtil.parseString(FrameTimeUtil.getTime(), FrameTimeUtil.FMT_YYYY);
				browseDateDir += "/" + FrameTimeUtil.parseString(FrameTimeUtil.getTime(), "MM-dd");
				String dateDir = FrameTimeUtil.parseString(FrameTimeUtil.getTime(), FrameTimeUtil.FMT_YYYY);
				dateDir += File.separator + FrameTimeUtil.parseString(FrameTimeUtil.getTime(), "MM-dd");
				sysName = FrameNoUtil.uuid() + "." + fileExt;

				String browseUrl = "/" + fileInfo.getType() + "/";
				String newFilePath = File.separator + fileInfo.getSystem() + File.separator + fileInfo.getType() + File.separator;
				if (FrameStringUtil.isNotEmpty(fileInfo.getTypeSecond())) {
					newFilePath += fileInfo.getTypeSecond() + File.separator;
					browseUrl += fileInfo.getTypeSecond() + "/";
				}
				newFilePath += dateDir + File.separator;
				browseUrl += browseDateDir + "/" + sysName;

				FrameFileUtil.createDir(savePath + newFilePath);
				File uploadFile = new File(savePath, newFilePath + sysName);
				multipartFile.transferTo(uploadFile);

				fileInfo.setBrowseUrl(browseUrl);
				fileInfo.setSavePath(savePath + newFilePath + sysName);
				Double fileSize = (double) (uploadFile.length() / 1024);
				fileInfo.setFileSize(fileSize);
				fileInfo.setSysName(sysName);
				fileInfo.setOrgName(orgName);
				frame = saveFileInfo(fileInfo);
			} catch (Exception e) {
				LOGGER.error(e.getMessage(), e);
				frame.setCode(ResponseCode.FAIL.getCode());
			} finally {
				if(inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException e) {
						LOGGER.error(e.getMessage(), e);
					}
				}
			}
		} else {
			frame.setCode(-3);
			frame.setMessage("上传文件的格式异常");
		}
		LOGGER.info("上传文件返回结果: " + FrameJsonUtil.toString(frame));
		return frame;
	}
}